package ru.bytedog.oiot.counter.bot.service;

import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.bytedog.oiot.counter.bot.bean.AppAuthority;
import ru.bytedog.oiot.counter.bot.bean.ErrorCode;
import ru.bytedog.oiot.counter.bot.dto.dashboard.UserInfo;
import ru.bytedog.oiot.counter.bot.entity.BotUser;
import ru.bytedog.oiot.counter.bot.exception.ServiceException;
import ru.bytedog.oiot.counter.bot.repository.BotUserRepository;


import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class UserService implements UserDetailsService {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm dd.MM.yy");

    private final BotUserRepository repository;
    private final ConfigService configService;

    public UserService(BotUserRepository repository, ConfigService configService) {
        this.repository = repository;
        this.configService = configService;
    }

    public BotUser create(BotUser user) {
        BotUser createdUser = getByChatId(user.getChatId());
        if (createdUser == null) {
            user.setCreateDate(LocalDateTime.now());
            user.setStep(RegisterUserStep.EMPTY_TOKEN);
            user.setRole(getRole(user.getUsername()));
            return repository.saveAndFlush(user);
        }
        return createdUser;
    }

    public void update(BotUser user) {
        repository.saveAndFlush(user);
    }

    public BotUser getByChatId(Long chatId) {
        Optional<BotUser> optional = repository.findById(chatId);
        if (optional.isEmpty()) {
            return null;
        }
        BotUser user = optional.get();
        setRoleIfEmpty(user);
        return user;
    }

    public List<BotUser> getAll() {
        return repository.findAll();
    }

    public Page<UserInfo> getAll(Pageable pageable) {
        Page<BotUser> users = repository.findAll(pageable);
        return users.map(this::mapBotToUserInfo);
    }

    public BotUser getByUsername(String username) throws ServiceException {
        Optional<BotUser> optional = repository.findByUserName(username);
        if (optional.isEmpty()) {
            throw new ServiceException(ErrorCode.USER_NOT_FOUND_BY_NAME, username);
        }
        BotUser user = optional.get();
        setRoleIfEmpty(user);
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            return getByUsername(username);
        } catch (ServiceException e) {
            throw new UsernameNotFoundException(e.getMessage());
        }
    }

    public void changeRole(String username, AppAuthority authority) throws ServiceException {
         BotUser user = getByUsername(username);
         user.setRole(authority.getRole());
         update(user);
    }

    private UserInfo mapBotToUserInfo(BotUser user) {
        return new UserInfo()
                .setId(user.getChatId())
                .setUsername(user.getUsername())
                .setFio(StringUtils.joinWith(StringUtils.SPACE, user.getFirstName(), user.getLastName()))
                .setStep(user.getStep().name())
                .setCreateDate(FORMATTER.format(user.getCreateDate()))
                .setAdditional(AppAuthority.ADMIN.getRole().equals(user.getRole()))
                .setRoot(configService.isAccessEnabled(user.getUsername()));
    }

    private String getRole(String username) {
        return configService.isAccessEnabled(username) ? AppAuthority.ADMIN.getRole() : AppAuthority.USER.getRole();
    }

    private void setRoleIfEmpty(BotUser user) {
        // Для старых пользователей у которых не установлена роль
        if (StringUtils.isBlank(user.getRole())) {
            user.setRole(getRole(user.getUsername()));
            update(user);
        }
    }
}
